<template>
  <div ref="line" class="comp"></div>
</template>

<script setup>
import { inject, ref, onMounted, onBeforeUnmount } from "vue";
const echarts = inject("echarts");
const api = inject("api");
// console.log(echarts);
// console.log(api);

// 初始化图标容器ref的值
let line = ref(null);

// 初始化echarts实例对象
let echartsInstance = null;
// 初始化数据业务
let allData = [];

function initEcharts() {
  echartsInstance = echarts.init(line.value, "dark");
  let initOptions = {
    title: {
      text: "农业种植生长趋势",
      top: "3%",
      left: "3%",
    },
    legend: {
      icon: "circle",
      top: "12%",
      left: "3%",
    },
    grid: {
      show: false,
      top: "20%",
      left: "3%",
      right: "3%",
      bottom: "3%",
      containLabel: true,
    },
    tooltip: {},
    xAxis: {
      type: "category",
    },
    yAxis: {
      type: "value",
    },
  };

  echartsInstance.setOption(initOptions);
}
async function getData() {
  let { data } = await api("CropGrowthTrend");
  console.log(data);

  allData = data;
  enitEcharts();
}
function enitEcharts() {
  let seriesData = allData.map((item) => {
    let datas = item.content.map((m) => m.area);
    return {
      name: item.city,
      type: "line",
      data: datas,
      stack: true,
      smooth: true,
      areaStyle: {}//堆叠填色
    };
  });
  let enitOptions = {
    xAxis: {
      data: allData[0].content.map((item) => item.month),
    },
    series: seriesData,
  };
  echartsInstance.setOption(enitOptions);
}
// 手动适配样式
function asisEcharts() {
  let width = line.value.offsetWidth;
  let scale = (width / 100) * 3.6;
  let initOptions = {
    title: {
      textStyle: {
        fontSize: scale,
      },
    },
    legend: {
      itemGap: scale / 2,
      itemHeight: scale / 2,
      itemWidth: scale / 2,
    },
  };
  echartsInstance.setOption(initOptions);
  echartsInstance.resize();
}
onMounted(() => {
  initEcharts(),
    getData(),
    window.addEventListener("resize", asisEcharts),
    asisEcharts();
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", asisEcharts);
});
defineExpose({
    asisEcharts
})
</script>

<style scoped></style>
